package com.share.PACManager.task;

import java.net.URLEncoder;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.share.PACManager.model.TerminalModel;
import com.share.PACManager.net.HTTPResponse;
import com.share.PACManager.net.HttpUtility;
import com.share.PACManager.utils.Cryptography;
import com.share.PACManager.utils.Utils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class RegDeviceTask extends Thread{

	private RegDeviceListener mListener;
	private Context mContext;
	private String mServer;
	
	private TerminalModel mTerminal;
	
	public interface RegDeviceListener 
	{
		public String requestServer();
		public TerminalModel requestTerminal();
		public void onCheckResult(boolean result, String server);
	}

	public RegDeviceTask(Context context) {
		mContext = context;
	}
	
	public void start(RegDeviceListener listener) {
		mListener = listener;
		if(mListener != null)
		{
			mServer = mListener.requestServer();
			mTerminal = mListener.requestTerminal();
			start();
		}
	}
	
	private Handler handler = new Handler(){		
		@Override
		public void handleMessage(Message msg)
		{
			if(mListener != null)
			{
				if(msg.what != 0)
					mListener.onCheckResult(false, mServer);
				else
				{
					HTTPResponse resp = (HTTPResponse) msg.obj;
					Utils.saveTmpFile(resp.toString());
					if(!parse(resp.content))
						mListener.onCheckResult(false, mServer);
					else
					{
						mListener.onCheckResult(true, mServer);
					}
				}
			}				
		}
	};
	
    public boolean parse(String json)
    {
		try {
			JSONObject jsonObject = new JSONObject(json);
			if(!jsonObject.getBoolean("Success"))
				return false;
			
			JSONObject state = jsonObject.getJSONObject("State"); 
			if(state != null)
			{
				mTerminal.TerminalId = Utils.getJsonString(state,"TerminalId");
				mTerminal.TerminalCode = Utils.getJsonString(state,"TerminalCode");
				mTerminal.TerminalPassword =Utils.getJsonString(state,"TerminalPassword");
				mTerminal.TerminalPhoneNumber = Utils.getJsonString(state,"TerminalPhoneNumber");
				mTerminal.TerminalType = Utils.getJsonString(state,"TerminalType");
				mTerminal.TerminalStatus = Utils.getJsonString(state,"TerminalStatus");
				mTerminal.TerminalArea = Utils.getJsonString(state,"TerminalArea");
				mTerminal.TerminalCreateTime = Utils.getJsonDate(state,"TerminalCreateTime");
				mTerminal.TerminalChangeTime = Utils.getJsonDate(state,"TerminalChangeTime");
				mTerminal.TerminalComment = Utils.getJsonString(state,"TerminalComment");
				
				return true;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return false;
    }
    
	@Override
	public void run() {	

		try {
			
			String terminalId = "Guest";
			String imei = Utils.getImei(mContext);
			String password = Cryptography.hashPassword("Password");
			String ticket = Cryptography.AES_Encode("IMEI", terminalId, password);
			String info = Cryptography.AES_Encode("IMEI=" + imei, terminalId, password);

			Map<String, String> params = new TreeMap<String, String>();
			params.put("Id", terminalId);
			params.put("DataType", "Data");	
			params.put("Password", password);
			params.put("TerminalCode", "IMEI");
			params.put("Version", "1.0");
			params.put("Ticket", ticket);
			params.put("Objective", "GetTerminal");
			
			String entity = "Information=" + URLEncoder.encode(info);	
			
			String uri = HttpUtility.getUrl(mServer);
			handler.obtainMessage(0, HttpUtility.httpPost(uri, params, entity)).sendToTarget();

		} catch (Exception e) {
			handler.obtainMessage(1).sendToTarget();
		}
		
		super.run();
	}	
	
	
}
